//
//  ZWPlayerViewController.m
//  WanEr
//
//  Created by 高文萍 on 16/1/19.
//  Copyright © 2016年 ziwokeji. All rights reserved.
//

#import "ZWPlayerViewController.h"
#import "ZWHeader.h"
#import "AppDelegate.h"
#import "ZWBoomTomView.h"
#pragma ----------scroller cityTable------
#import "ZWCitySSTableViewCell.h"
#import "ZWCitySSHeaderView.h"// 245H
#pragma ----------scroller playerView-----
#import "ZWPlayerSSView.h"
#pragma ----------scroller text Img--------
#import "ZWBaseCollecView.h"
#import "ZWSSThreeCollectionCell.h"
#import "ZWPlayerModel.h"
#import "ZWSSThreeTextView.h"
#pragma ---------播放-----
//#import "PlayerManager.h"
#import "ZWBoomTomView.h"// 切换歌曲
#import "ZWPlayerSSView.h"// 滑条
#import <AVFoundation/AVFoundation.h>

@interface ZWPlayerViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource>
#pragma ---导航栏---
@property (nonatomic, strong) UIView *headerPlayerView;
@property (nonatomic, strong) UIImageView *headerPImg;
@property (nonatomic, strong) UILabel *headerPLabel;
@property (nonatomic, strong) UIButton *returnPBut;
@property (nonatomic, strong) UIButton *sharePBut;
#pragma ---底部显示栏---
@property (nonatomic, strong) ZWBoomTomView *boomtomView;
@property (nonatomic, strong) UIScrollView *allBigScroll;
@property (nonatomic, strong) UIView *pageView;// 滑动小条

#pragma ---scroller上四个试图
//第一个table city列表
@property (nonatomic, strong) UITableView *cityTable;
@property (nonatomic, strong) NSMutableArray *cityArr;
@property (nonatomic, strong) ZWCitySSHeaderView *citySSHeaderView;
//第二个播放页
@property (nonatomic, strong) ZWPlayerSSView *playerSSView;
@property (nonatomic, strong) UIImageView *playerImg;
// 第三个文字图片切换
@property (nonatomic, strong) UIScrollView *textScroller;
@property (nonatomic, strong) UILabel *threeTextLabel;
@property (nonatomic, strong) ZWSSThreeTextView *threeTextView;
@property (nonatomic, strong) ZWBaseCollecView *threeCollection;
@property (nonatomic, strong) ZWSSThreeCollectionCell *threeCell;
@property (nonatomic, strong) UIButton *changeTextBut;
@property (nonatomic, strong) UIButton *changeImgBut;
@property (nonatomic, assign) BOOL select;
@property (nonatomic, strong)NSMutableAttributedString *TextAttributed;
// 点三个scroller collection点击循环图片
@property (nonatomic, strong) UIScrollView *imgScroller;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, assign) NSInteger iImg;
@property (nonatomic, strong) UIButton *but;
#pragma -----数据所需------
@property (nonatomic, strong) NSMutableArray *scrollImgArr;
@property (nonatomic, strong) NSMutableDictionary *scrollerDic;
@property (nonatomic, strong) NSMutableArray *arr;
// slider滑条 切换
//@property (nonatomic, strong) PlayerManager *playManager;
@property (nonatomic, strong) ZWBoomTomView *playerChangeView;
@property (nonatomic, strong) ZWPlayerSSView *sliderView;
@end

@implementation ZWPlayerViewController
// 执行播放
+ (ZWPlayerViewController *)defaultManager
{
    static ZWPlayerViewController *defaultManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defaultManager = [[ZWPlayerViewController alloc]init];
        
        //激活音频会话
//        [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
//        [[AVAudioSession sharedInstance]setActive:YES error:nil];
    });
    
    return defaultManager;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 播放小条
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    tempAppDelegate.audioStudioView.hidden = YES;
    
    // 调用准备播放的歌曲同时获取到MusicInfo
    [self.playerSSView prepareMusic:self.musicIndex];
   
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    tempAppDelegate.audioStudioView.hidden = NO;

}
#pragma --------先执行-------
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createHeaderLan];// 顶部视图
    [self boomtomViewCreate];// 底部视图
    [self createScroller];// scroller
    [self createCityPage];// 第一个page
    [self createPlayerPage];// 第二个page
    [self createWebPage];// 第三个page
    
    [self createData];
    
    // 播放执行的协议方法
//    self.playManager = [PlayerManager playerManager];
//    self.playManager.delegate = self;
    
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(timeChange:)//接收消息方法
//                                                 name:@"totalTime"//消息识别名称
//                                               object:nil];
    
}

//-(void)timeChange:(NSNotification *)notif{
////    notif.userInfo
//    NSString *time = [notif.userInfo objectForKey:@"time"];
//    [self didPlayChangeStatus:time];
//}

- (void)createData
{
    self.scrollerDic = [NSMutableDictionary dictionary];
    self.scrollImgArr = [NSMutableArray array];
    self.arr = [NSMutableArray array];
    [JXRAFNetWorkTool getNetWithURL:[NSString stringWithFormat:@"http://app.ziwoxz.com/agi/scenerie/detail_info/sid/%@", self.uId] body:self resultKind:JXRJSON headerFile:nil success:^(id result) {
       
        self.scrollImgArr = result[@"data"][@"scenerie"][@"images"];
        self.scrollerDic = result[@"data"][@"scenerie"];
        self.arr = [ZWPlayerModel baseModelByArr:self.scrollerDic[@"belongs"] arr:self.arr];
        
        [self.cityTable reloadData];
        [self.threeCollection reloadData];
    } failure:^(NSError *error) {
        
    }];
}
#pragma ---顶部导航来创建---
- (void)createHeaderLan
{
    // 顶部菜单栏
    self.headerPlayerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.view addSubview:self.headerPlayerView];
    self.headerPImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.headerPlayerView addSubview:self.headerPImg];
    self.headerPImg.image = [UIImage imageNamed:@"iOS顶部菜单栏"];
    self.headerPLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    [self.headerPlayerView addSubview:self.headerPLabel];
    [self.headerPLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerPlayerView.mas_centerX);
        make.bottom.equalTo(self.headerPlayerView.mas_bottom).offset(-10);
        make.height.equalTo(@(20));
    }];
    
    self.sharePBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.sharePBut setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
    [self.sharePBut addTarget:self action:@selector(headerClick:) forControlEvents:UIControlEventTouchUpInside];
    self.sharePBut.tag = 100;
    [self.headerPlayerView addSubview:self.sharePBut];
    [self.sharePBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(-15));
        make.bottom.equalTo(self.headerPlayerView.mas_bottom).offset(-10);
        make.width.height.equalTo(@(23));
    }];
    
    self.returnPBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.returnPBut setImage:[UIImage imageNamed:@"Oval 36 + Path 43 + Path 44 + Path 44 Copy-1"] forState:UIControlStateNormal];
    self.returnPBut.tag = 101;
    [self.returnPBut addTarget:self action:@selector(headerClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerPlayerView addSubview:self.returnPBut];
    [self.returnPBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(16));
        make.bottom.equalTo(self.headerPlayerView.mas_bottom).offset(-10);
        make.width.equalTo(@(25));
        make.height.equalTo(@(25));
    }];
    
    
    
    
}
- (void)headerClick:(UIButton *)button
{
    if (button.tag == 100) {
        NSLog(@"分享");
    }else if (button.tag == 101){
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma ---底部试图创建---
- (void)boomtomViewCreate
{
    self.boomtomView = (ZWBoomTomView *)[[[NSBundle mainBundle]loadNibNamed:@"bootomView" owner:self options:nil] lastObject];
    self.boomtomView.frame = CGRectMake(0, HEIGHT - 100, WIDTH, 100);
    [self.view addSubview:self.boomtomView];
    
        for (NSInteger i; i < 3; i ++) {
            
            self.pageView = [[UIView alloc]init];
            self.pageView.frame = CGRectMake(i * 40, 0, 20, 2);
            self.pageView.backgroundColor = [UIColor colorWithWhite:0.849 alpha:1.000];
            [self.boomtomView.pageView addSubview:self.pageView];
            
  }
 }


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pageView.backgroundColor = [UIColor orangeColor];
}
#pragma ---滑动试图创建---
- (void)createScroller
{
    self.allBigScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64 - 100)];
    self.allBigScroll.contentSize = CGSizeMake(WIDTH * 3, 0);
    self.allBigScroll.pagingEnabled = YES;
    self.allBigScroll.bounces = NO;
    self.allBigScroll.contentOffset = CGPointMake(WIDTH, 0);
    self.allBigScroll.delegate = self;
    self.allBigScroll.alwaysBounceHorizontal = NO;
    self.allBigScroll.alwaysBounceVertical = NO;
    self.allBigScroll.showsHorizontalScrollIndicator = NO;
    self.allBigScroll.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.allBigScroll];
}
#pragma ---第一个scroller tableView---------------
- (void)createCityPage
{
    self.cityTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 100) style:UITableViewStylePlain];
    self.cityTable.delegate = self;
    self.cityTable.dataSource = self;
    self.cityTable.rowHeight = 60;
    [self.allBigScroll addSubview:self.cityTable];
    self.citySSHeaderView = (ZWCitySSHeaderView *)[[[NSBundle mainBundle]loadNibNamed:@"citySSHeader" owner:self options:nil] lastObject];
    self.citySSHeaderView.frame = CGRectMake(0, 0, WIDTH, 245);
    self.cityTable.tableHeaderView = self.citySSHeaderView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 第一个scroller
    self.citySSHeaderView.cityText.text = self.scrollerDic[@"area"];
    self.citySSHeaderView.jingjiText.text = self.scrollerDic[@"scenerie_name"];
    self.citySSHeaderView.yuanwenText.text = self.scrollerDic[@"content_creater"];
    self.citySSHeaderView.zhuboText.text = self.scrollerDic[@"recording_creater"];
    self.citySSHeaderView.allTitleText.text = [self.scrollerDic[@"scenerie_name"] stringByAppendingString:@"全部景点"];
    [self.playerImg sd_setImageWithURL:[NSURL URLWithString:self.scrollerDic[@"second_image_url"]]placeholderImage:[UIImage imageNamed:@"首页占位图"]];
    // 标题
    self.headerPLabel.text = self.scrollerDic[@"scenerie_name"];
    
    // 第三个scroller
    [self.threeTextView.textImg sd_setImageWithURL:[NSURL URLWithString:self.scrollerDic[@"second_image_url"]]placeholderImage:[UIImage imageNamed:@"首页占位图"]];
    // 下部分文字
    self.threeTextLabel.text = self.scrollerDic[@"content"];
    
    self.threeTextView.cityLabel.text = self.scrollerDic[@"scenerie_name"];// xib
    self.threeTextView.wenLabel.text = self.scrollerDic[@"content_creater"];
    self.threeTextView.yinLable.text = self.scrollerDic[@"recording_creater"];
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cityReuse = @"cityReuse";
    ZWCitySSTableViewCell *cityCell = [tableView dequeueReusableCellWithIdentifier:cityReuse];
    if (!cityCell) {
        cityCell = [[ZWCitySSTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cityReuse];
    }
    NSString *str = @"by:";
    ZWPlayerModel *model = (ZWPlayerModel *)self.arr[indexPath.row];
    cityCell.cityNamLabel.text = model.scenerie_name;
    cityCell.byLabel.text = [str stringByAppendingString:@"宇宙"];
    [cityCell.downLoadBut setImage:[UIImage imageNamed:@"封面下载"] forState:UIControlStateNormal];
    [cityCell.downLoadBut addTarget:self action:@selector(downLoadButClick:) forControlEvents:UIControlEventTouchUpInside];
    return cityCell;
}
- (void)downLoadButClick:(UIButton *)button
{
    NSLog(@"下载");
}

#pragma ----第二个scroller  playerView------------
- (void)createPlayerPage
{
    self.playerImg = [[UIImageView alloc]initWithFrame:CGRectMake(46 + WIDTH, 50, WIDTH - 92, WIDTH - 92)];
    [self.allBigScroll addSubview:self.playerImg];
    self.playerSSView = (ZWPlayerSSView *)[[[NSBundle mainBundle]loadNibNamed:@"Empty" owner:self options:nil] lastObject];
    self.playerSSView.frame = CGRectMake(WIDTH, self.playerImg.frame.size.height + 50, WIDTH, self.allBigScroll.frame.size.height - self.playerImg.frame.size.height);
    [self.allBigScroll addSubview:self.playerSSView];
}

#pragma ----第三个scroller Web Img----------------
- (void)createWebPage
{
    self.threeCollection = [[ZWBaseCollecView alloc]initWithFrame:CGRectMake(WIDTH * 2, 50, WIDTH, self.allBigScroll.frame.size.height - 50) flowLayoutItemSize:CGSizeMake((WIDTH - 15 * 2 - 3 * 2) / 3, (WIDTH - 15 * 2 - 3 * 2) / 3) xSpace:3 ySpace:0 sectionInset:UIEdgeInsetsMake(3, 15, 3, 15) cell:[ZWSSThreeCollectionCell class] reuse:@"threeCollection"];
    self.threeCollection.delegate = self;
    self.threeCollection.dataSource = self;
    [self.allBigScroll addSubview:self.threeCollection];
    
    self.textScroller = [[UIScrollView alloc]initWithFrame:CGRectMake(WIDTH * 2, 0, WIDTH, self.allBigScroll.frame.size.height)];
    self.textScroller.delegate = self;
    [self.allBigScroll addSubview:self.textScroller];
    self.textScroller.backgroundColor = [UIColor whiteColor];
    self.textScroller.contentOffset = CGPointMake(0, 0);
    self.textScroller.pagingEnabled = NO;
    self.threeTextView = (ZWSSThreeTextView *)[[[NSBundle mainBundle]loadNibNamed:@"threeText" owner:self options:nil]lastObject];
    self.threeTextView.frame = CGRectMake(0, 0, WIDTH, 350);
    [self.textScroller addSubview:self.threeTextView];// 上部分xib视图
    
    // 下部分文字
    //初始化label
    self.threeTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 375,WIDTH - 20, 20)];
    //设置自动行数与字符换行
    [self.threeTextLabel setNumberOfLines:0];
    self.threeTextLabel.lineBreakMode = UILineBreakModeWordWrap;
    self.threeTextLabel.font = [UIFont systemFontOfSize:16];
    self.threeTextLabel.text = @"sajfksjfsjdfksj的萨芬";// 传值上的问题
    //自适应高度
    CGRect txtFrame = self.threeTextLabel.frame;
    self.threeTextLabel.frame = CGRectMake(15,375,WIDTH - 30, txtFrame.size.height =[self.threeTextLabel.text boundingRectWithSize:CGSizeMake(txtFrame.size.width, CGFLOAT_MAX)options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.threeTextLabel.font,NSFontAttributeName, nil] context:nil].size.height);
    self.threeTextLabel.frame = CGRectMake(10,375,WIDTH - 20, txtFrame.size.height);
    [self.textScroller addSubview:self.threeTextLabel];
    self.textScroller.contentSize = CGSizeMake(WIDTH, self.threeTextView.frame.size.height + self.threeTextLabel.frame.size.height + 30);// scroller偏移量
   
    
    // 按钮切换问题 图片视图
    self.changeImgBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.changeImgBut.frame = CGRectMake(WIDTH * 3 - 70, 10, 60, 30);
    self.changeImgBut.tag = 1000;
    [self.changeImgBut addTarget:self action:@selector(threeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.changeImgBut setImage:[UIImage imageNamed:@"图2"] forState:UIControlStateNormal];
    [self.allBigScroll addSubview:self.changeImgBut];

    self.changeTextBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.changeTextBut.tag = 1001;
    [self.changeTextBut addTarget:self action:@selector(threeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.changeTextBut setImage:[UIImage imageNamed:@"文2"] forState:UIControlStateNormal];
    [self.allBigScroll addSubview:self.changeTextBut];
    [self.changeTextBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.changeImgBut.mas_centerY);
        make.right.equalTo(self.changeImgBut.mas_left).offset(0);
        make.width.equalTo(@(60));
        make.height.equalTo(@(30));
    }];
    
}
// 图片循环展示
- (void)createImgScroller
{
    self.imgScroller = [[UIScrollView alloc]initWithFrame:CGRectMake(WIDTH * 2, 0, self.threeCollection.contentSize.width, self.threeCollection.contentSize.height)];
    self.imgScroller.backgroundColor = [UIColor whiteColor];
    //按页来进行滚动
    self.imgScroller.pagingEnabled = YES;
    self.imgScroller.contentSize = CGSizeMake(WIDTH * self.scrollImgArr.count, HEIGHT);
    self.imgScroller.contentOffset = CGPointMake(self.iImg * WIDTH, 0);
    self.imgScroller.delegate = self;
    [self.allBigScroll addSubview:self.imgScroller];
    //关掉边界回弹效果 默认是YES
    self.imgScroller.bounces = NO;
    //关闭滚动条
    self.imgScroller.showsHorizontalScrollIndicator = NO;
    self.imgScroller.showsVerticalScrollIndicator = NO;
    // 收回按钮
    UIButton *imgBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [imgBut setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
    imgBut.frame = CGRectMake(WIDTH - 45, 74, 25, 25);
    [imgBut addTarget:self action:@selector(imgButClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:imgBut];
    self.but = imgBut;

}
// 点击图片收回
- (void)imgButClick:(UIButton *)button
{
    [self.but removeFromSuperview];
    self.imgScroller.frame = CGRectMake(WIDTH * 2, HEIGHT, WIDTH, HEIGHT);
    NSLog(@"缩回");
    self.headerPlayerView.hidden = NO;
    self.boomtomView.hidden = NO;
}
// 按钮切换样式 --文字 图片
- (void)threeClick:(UIButton *)button
{
    if (button.tag == 1000) {
        [self.changeTextBut setImage:[UIImage imageNamed:@"文1"] forState:UIControlStateNormal];
        [self.changeImgBut setImage:[UIImage imageNamed:@"图1"] forState:UIControlStateNormal];
        self.threeCollection.hidden = NO;
        self.textScroller.hidden = YES;
    }else{
        [self.changeTextBut setImage:[UIImage imageNamed:@"文2"] forState:UIControlStateNormal];
        [self.changeImgBut setImage:[UIImage imageNamed:@"图2"] forState:UIControlStateNormal];
        self.threeCollection.hidden = YES;
        self.textScroller.hidden = NO;
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.scrollImgArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.threeCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"threeCollection" forIndexPath:indexPath];
    
    [self.threeCell.ssThreeImg sd_setImageWithURL:[NSURL URLWithString:self.scrollImgArr[indexPath.row]]placeholderImage:[UIImage imageNamed:@"筛选后占位图"]];
    return self.threeCell;
}
// 点击图片放大
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.iImg = indexPath.row;
    // 图片循环
    [self createImgScroller];
    [UIView animateWithDuration:0.02 animations:^{
        self.imgScroller.frame = CGRectMake(WIDTH * 2, 0, WIDTH, HEIGHT);
        for (NSInteger i = 0; i<self.scrollImgArr.count; i++) {
            //通过图片名来创建UIImageView
            self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH * i , 0, WIDTH, HEIGHT)];
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.scrollImgArr[i]]];// 取到所有图片下标
            //把imageView放到scrollview上
            [self.imgScroller addSubview:self.imageView];
        }
    }];

    self.headerPlayerView.hidden = YES;
    self.boomtomView.hidden = YES;
    
}

// 播放执行的方法
#pragma mark - Player Manager Delegate
//-(void)didPlayChangeStatus:(NSString *)time{
//    // NSLog(@"音乐在播放");
//    
//    [self.sliderView playMusicWithFormatString:time];
//    // 动画
//}

- (void)didMusicCutWithMusicInfo:(ZWPlayerModel *)musicInfo{
    
    // 控制台
//      self.playerConsole.duration = [[self.playManager getDurationFromPlayer]floatValue];
    [self.sliderView prepareMusicInfo:musicInfo];
    [self.playerImg sd_setImageWithURL:[NSURL URLWithString:musicInfo.image_url]placeholderImage:[UIImage imageNamed:@"首页占位图"]];
    self.headerPLabel.text = musicInfo.scenerie_name;
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
